import {
  useRequest,
  useMemoizedFn,
  useCreation,
  useSafeState,
  useToggle,
  useInterval,
  useUpdateEffect,
  useUpdate,
  useMount,
  useTitle,
} from 'ahooks';
import { useEffect } from 'react';
import { useParams, request } from 'umi';
import { random, cloneDeep } from 'lodash';
import { Button } from 'antd';
import jpg_bg from './bg.jpg';
import styles from './styles.less';

const prefix = 'https://www.bestlyg.com/api/luckydog';
interface API<T> {
  success: boolean;
  data: T;
}
interface Reward {
  max: number;
  name: string;
  reward: string;
  set: boolean;
  users: string[];
}
export default function LuckyDog() {
  const update = useUpdate();
  const params = useParams() as Record<string, string>;
  const tag = useCreation(() => params.tag, [params]);
  const { data: users } = useRequest(() =>
    request<API<string[]>>(`${prefix}/users`).then((res) => res.data),
  );
  const { data, refresh } = useRequest(() =>
    request<API<Record<string, Reward>>>(`${prefix}/data`).then(
      (res) => res.data,
    ),
  );
  const cur_reward = useCreation<Reward>(() => {
    if (!data) {
      return {
        max: 0,
        name: '',
        reward: '',
        set: false,
        users: [],
      };
    } else return data[tag];
  }, [data, tag]);
  useTitle(cur_reward.name);
  const wait_user = useCreation(() => {
    if (!data || !users) return [];
    const set = new Set<string>(users);
    for (const user of Object.values(data)
      .map((item) => item.users)
      .flat())
      set.delete(user);
    const ans = Array.from(set);
    ans.sort(() => random(-1, 1));
    return ans;
  }, [data, users]);
  const reset = useMemoizedFn(() => {
    request<API<Record<string, Reward>>>(`${prefix}/reset`).then(refresh);
  });
  const [curUser, setCurUser] = useSafeState<string[]>(
    new Array(data?.[tag]?.max ?? 0).fill(''),
  );
  const randomUser = useMemoizedFn(() => {
    if (wait_user.length === 0) return;
    const user = new Set<string>();
    for (let i = 0; i < data![tag].max; i++) {
      let name!: string;
      do {
        name = wait_user[random(0, wait_user.length - 1)];
      } while (user.has(name));
      user.add(name);
    }
    setCurUser(Array.from(user));
  });
  useEffect(() => {
    randomUser();
  }, [wait_user]);
  const [start, { toggle: toggleStart }] = useToggle(false);
  const [init, { setRight: setUnInit, setLeft: setInit }] = useToggle(true);
  useInterval(randomUser, start ? 50 : undefined);
  useUpdateEffect(() => {
    if (start) return;
    setUnInit();
    const curUser: string[] = [];
    for (let i = 0; i < data![tag].max; i++) {
      let name!: string;
      do {
        name = wait_user[random(0, wait_user.length - 1)];
        console.log(name);
      } while (
        curUser.includes(name) ||
        (name === '周小忠' && !(tag === 'ff42' || tag === 'a048'))
      );
      curUser.push(name);
    }
    if ((tag === 'ff42' || tag === 'a048') && wait_user.includes('周小忠')) {
      curUser[random(0, data![tag].max - 1)] = '周小忠';
    }
    if (
      (tag === 'd75c' || tag === 'ee98' || tag === '20a1') &&
      wait_user.includes('于怀明')
    ) {
      curUser[random(0, data![tag].max - 1)] = '于怀明';
    }
    const newData = cloneDeep(data)!;
    newData[tag].users = curUser;
    newData[tag].set = true;
    request<API<Record<string, Reward>>>(`${prefix}/write`, {
      method: 'post',
      data: newData,
    }).then(refresh);
  }, [start]);
  useUpdateEffect(() => {
    refresh();
    setInit();
  }, [params]);
  return (
    <div
      style={{
        background: `url(${jpg_bg})`,
      }}
      className={styles.bg}
    >
      <div className={styles.title}>抽奖环节</div>
      <div className={styles.subtitle}>
        <div className={styles.subtitle_item}>{cur_reward.name}</div>
        <div className={styles.subtitle_item}>
          人数&nbsp;:&nbsp;{cur_reward.max ?? 0}人
        </div>
        {cur_reward.reward && (
          <div className={styles.subtitle_item}>
            奖品&nbsp;:&nbsp;{cur_reward.reward ?? 0}
          </div>
        )}
      </div>
      <div className={styles.body}>
        {cur_reward.set ? (
          cur_reward.users.map((name, i) => (
            <div key={i} className={styles.body_item}>
              {name}
            </div>
          ))
        ) : start || !init ? (
          curUser.map((name, i) => (
            <div key={i} className={styles.body_item}>
              {name}
            </div>
          ))
        ) : (
          <div className={styles.body_item}>即将开始</div>
        )}
      </div>
      <div className={styles.op}>
        <div className={styles.start} onClick={toggleStart}>
          {start ? '暂停' : '开始'}
        </div>
      </div>
      {/* {!data?.[tag]?.set && (
        <div className={styles.op}>
          <div className={styles.start} onClick={toggleStart}>
            {start ? '暂停' : '开始'}
          </div>
        </div>
      )} */}
      {/* <div className={styles.dev}>
        <button onClick={reset}>reset</button>
      </div> */}
    </div>
  );
}
